#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>   // bind()

using std::cout;
using std::endl;
using std::string;

class TranslateClient
{
public:
    TranslateClient(const string& sip, int port): _latch(1), _client(
        _loopthread.startLoop(), 
        muduo::net::InetAddress(sip, port), 
        "TranslateClient")
    {
        // 将类成员函数设置为服务器的回调处理函数
        _client.setConnectionCallback(std::bind(
            &TranslateClient::onConnection,
            this, std::placeholders::_1
        ));

        _client.setMessageCallback(std::bind(
            &TranslateClient::onMessage, 
            this, std::placeholders::_1, 
            std::placeholders::_2, std::placeholders::_3
        ));
    }

    void connect()
    {
        _client.connect();
        _latch.wait();
    }

    bool send(const string& msg)
    {
        if(_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }


private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        // 新连接建立成功时的回调函数
        if(conn->connected())
        {
            _latch.countDown();
            _conn = conn;
        }
        else{
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        // 通信连接收到请求时的回调函数
        cout << "翻译结果：" << buf->retrieveAllAsString() << endl;
    }
private:
    // _loopthread是epoll的事件监控，会在子线程中进行描述符的事件监控，触发事件后进行io操作
    muduo::net::EventLoopThread _loopthread;
    // _client用于设置回调函数，告诉客户端收到什么请求该如何处理
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    // 为connect提供异步阻塞
    muduo::CountDownLatch _latch;
};

int main()
{
    TranslateClient client("127.0.0.1", 8085);
    client.connect();

    string msg = "";
    while(true)
    {
        std::cin >> msg;
        client.send(msg);
    }

    return 0;
}